import json
import requests

from test_case.common import TEST_TOPIC, GRAB_API_URL
from test_case.kafka_consumer_connect import KafkaConsumerConnect


def request_grab_api(red_envelope_id, user_name):
    """访问抢红包api"""
    headers = {
        "X-Apig-AppCode": "",
        "X-stage": "RELEASE",
        "host": "",
    }
    data = {
        "redEnvelopeId": red_envelope_id,
        "topicId": TEST_TOPIC,
        "userName": user_name,
    }
    res = requests.post(GRAB_API_URL, json=data, headers=headers, verify=False)
    return res


def user_grab_red_envelope(num):
    """用户监听消息，并准备抢红包"""
    print("{0}用户开始监听".format(num))
    user_name = "user_{0}".format(num)
    connect = KafkaConsumerConnect(TEST_TOPIC, user_name)
    for msg in connect.consumer:
        value = json.loads(msg.value.decode("utf-8"))
        if value.get("messageType") == 2:
            res = request_grab_api(value.get("redEnvelopeId"), user_name)
            response = res.json()
            try:
                print("-------> {0}".format(response.get("message")))
                for i in response.get("redEnvelopeInfo"):
                    print("用户：{0}，抢到红包：{1}，时间：{2}".format(
                        i["userName"], i["getMoney"], i["localTime"]))
            except Exception as e:
                print(response)
                print("出错了：{0}".format(e))
        print(value.get("msg"))


if __name__ == '__main__':
    import sys
    args = sys.argv
    number = args[1]
    user_grab_red_envelope(number)
